<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import JFormContainer from '@comp/jeecg/JFormContainer.vue'
import dayjs from 'dayjs'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import { getAction, postAction, putAction,httpAction } from '@api/manage'

export default {
  name: 'QcPlanReportBatchForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    reportType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      model: {
        inspectionResult: 1,
        inspectionDate: dayjs().format('YYYY-MM-DD')
      },
      validatorRules: {},
      // 检验报告单
      qcPlanReportTable: {
        loading: false,
        dataSource: [],
        columns: []
      },
      // 检验单检验项目表
      qcPlanReportInspectionItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验项目',
            key: 'itemName',
            type: JVXETypes.normal,
            minWidth: '200px'
          },
          {
            title: '上限值',
            key: 'upperLimit',
            type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '标准值',
            key: 'qualityStandard',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '下限值',
            key: 'lowerLimit',
            type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '结果录入',
            key: 'result',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            width:"200px",
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            minWidth:"200px",
            defaultValue:'',
          },
        ]
      },
      // 检验单项表
      qcPlanReportItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '订单编号',
            key: 'orderNumber',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            type: JVXETypes.normal,
            width: '200px'
          }
        ]
      },
      url: {
        addBatch: '/qms/inspection/plan/report/addBatch',
        editBasePowder: '/qms/inspection/plan/report/editBasePowder',
        workPlan: {
          list: '/wms/inbound/work-inbound-record/listWorkPlans'
        },
        basePowderInspectionStandardItem: {
          list: '/basiccheck/eneBasicCheck/queryEneBasicCheckDetailByMainId'
        },
        semiFinishedProductInspectionStandardItem: {
          list: '/semifinished/eneSemiFinishedCheck/queryEneSemiFinishedCheckDetailByMainId'
        },
        finishedProductInspectionStandardItem: {
          list: '/finishedproduct/eneFinishedProductCheck/queryEneFinishedProductCheckDetailByMainId'
        },
        qcPlanReportInspection: {
          list: '/qms/inspection/plan/report/queryQcPlanReportInspectionByMainId'
        },
        qcPlanReportItem: {
          list: '/qms/inspection/plan/report/queryQcPlanReportItemByMainId'
        },
      }, 
      currentWorkshopPlanId: null,
      cardList: [ // 存储所有卡片数据
        {
          standardId: null,
          inspectionDate: dayjs().format('YYYY-MM-DD'),
          inspectionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          inspectionResult: 1, // 默认为合格
          remark: '',
          inspectionItems: [] // 检验项目数据
        }
      ],
      currentCardIndex: 0, // 当前激活的卡片索引
      isEdit: false,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    inspectionStandardCode() {
      if (this.reportType === 'base-powder') {
        return 'ene_basic_check,check_standard,id'
      } else if (this.reportType === 'semi-finished-product') {
        return 'ene_semi_finished_check,check_standard,id'
      } else if (this.reportType === 'finished-product') {
        return 'ene_finished_product_check,check_standard,id'
      }
      return ''
    },
    inspectionStandardItemUrl() {
      if (this.reportType === 'base-powder') {
        return this.url.basePowderInspectionStandardItem.list
      } else if (this.reportType === 'semi-finished-product') {
        return this.url.semiFinishedProductInspectionStandardItem.list
      } else if (this.reportType === 'finished-product') {
        return this.url.finishedProductInspectionStandardItem.list
      }
      return ''
    },
    qcPlanReportTableColumns() {
      const columns = [
        {
          title: '计划单号',
          key: 'planNumber',
          type: JVXETypes.normal,
          width: '140px'
        }
      ]
      if (this.reportType === 'base-powder') {
        columns.push({
          title: '基粉配方',
          key: 'basePowderFormula',
          type: JVXETypes.input,
          placeholder: '请输入${title}',
          validateRules: [{ required: true, message: '${title}不能为空' }]
        })
      } else if (this.reportType === 'semi-finished-product') {
        columns.push({
          title: '配方号',
          key: 'basePowderFormula',
          type: JVXETypes.slot,
          validateRules: [{ required: true, message: '请选择${title}' }],
          slotName: 'formula'
        })
      }
      columns.push({
        title: '抽检数量',
        key: 'samplingQuantity',
        type: JVXETypes.inputNumber,
        placeholder: '请输入${title}'
      })
      return columns
    },
    qcPlanReportItemList() {
      if(this.isEdit){
        return this.qcPlanReportItemTable.dataSource;
      }
      if (!this.currentWorkshopPlanId) {
        return []
      }
      return this.qcPlanReportItemTable.dataSource.filter(item => {
        return item.workshopPlanId === this.currentWorkshopPlanId
      })
    }
  },
  methods: {
    add(records) {
      this.isEdit = false;
      this.qcPlanReportTable.dataSource = records.map(item => {
        return {
          workshopPlanId: item.id,
          reportType: this.reportType,
          planNumber: item.code,
          productionShop: item.workshopCode,
          executionDate: item.workTime
        }
      })
      this.fetchWorkshopPlanInfo(records.map(item => item.id))
    },
    edit(records) {
      this.isEdit = true;
      this.qcPlanReportInspectionItemTable.dataSource = []
      this.qcPlanReportItemTable.dataSource = []
      this.qcPlanReportTable.dataSource = []
      this.qcPlanReportTable.dataSource.push(JSON.parse(JSON.stringify(records)));
      this.model = records
      getAction(this.url.qcPlanReportInspection.list, { id: records.id }).then(res => {
        if (res.success && res.result) {
          this.cardList = res.result.map(item => ({
            ...item,
            inspectionItems: item.qcPlanReportInspectionItemList || []
          }));
        }
      });
      getAction(this.url.qcPlanReportItem.list, { id: records.id }).then(res => {
        if (res.success && res.result) {
          this.qcPlanReportItemTable.dataSource = res.result;
        }
      })
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      // const errMap = await this.$refs.qcPlanReportInspectionItem.validateTable()
      // if (errMap) {
      //   return
      // }
      // const errMap2 = await this.$refs.qcPlanReport.validateTable()
      // if (errMap2) {
      //   return
      // }
      let standardId = null;
      let remark = null;
      let inspectionResult = 1;
      if(this.reportType != 'base-powder' && this.cardList.length > 0){
        standardId = this.cardList[0].standardId
        remark = this.cardList[0].remark
        inspectionResult = this.cardList[0].inspectionResult
      }
      let formDataList;
      if(!this.isEdit){
        formDataList = this.qcPlanReportTable.dataSource.map(item => {
          return {
            ...item,
            id: null,
            standardId: standardId,
            inspectionDate: this.model.inspectionDate,
            inspectionResult: inspectionResult,
            remark: remark,
            qcPlanReportItemList: this.qcPlanReportItemTable.dataSource
              .filter(reportItem => reportItem.workshopPlanId === item.workshopPlanId)
              .map(item => ({
                ...item,
                id: null 
              })),
            qcPlanReportInspectionList: this.cardList.map(item => ({
                ...item,
                inspectionDate: this.model.inspectionDate,
                id: null,
                qcPlanReportInspectionItemList: item.inspectionItems.map(item => ({
                  ...item,
                  id: null 
                }))
              }))
          }
        })
      }else {
        let editData = this.qcPlanReportTable.dataSource.map(item => {
          return {
            ...item,
            inspectionDate: this.model.inspectionDate,
            qcPlanReportItemList: this.qcPlanReportItemTable.dataSource,
            qcPlanReportInspectionList: this.cardList.map(item => ({
                ...item,
                inspectionDate: this.model.inspectionDate,
                qcPlanReportInspectionItemList: item.inspectionItems,
              }))
          }
        })
        if(editData?.length > 0){
          formDataList = editData[0]
        }else {
          formDataList = editData
        }
      }
      this.request(formDataList)
    },
    request(formData) {
      const that = this;
      this.confirmLoading = true
      let httpurl = '';
      let method = '';
      if(!this.isEdit){
        httpurl+=this.url.addBatch;
        method = 'post';
      }else{
        httpurl+=this.url.editBasePowder;
        method = 'put';
      }
      httpAction(httpurl,formData,method).then((res)=>{
        if(res.success){
          that.$message.success(res.message);
          that.$emit('ok');
        }else{
          that.$message.warning(res.message);
        }
      }).finally(() => {
        that.confirmLoading = false;
      })
    },
    handleInspectionStandardChange(value, index) {
      const params = { id: value==null || value == undefined?'':value };
      getAction(this.inspectionStandardItemUrl, params).then(res => {
        if (res.result) {
          this.$set(this.cardList[index], 'inspectionItems', res.result.map(item => ({
            inspectionStandardId: item.basicId || item.semiId || item.finishedId,
            itemName: item.analyseItem,
            qualityStandard: item.qualityIndex,
            upperLimit: item.upperLimit,
            lowerLimit: item.lowerLimit,
            remark: item.remark,
            result: ''
          })));
        }
      });
    },
  
    handleDelete({ deleteRows }, index) {
    const items = this.cardList[index].inspectionItems;
    this.cardList[index].inspectionItems = items.filter(row => 
      !deleteRows.some(item => item.id === row.id))
    },
    handleSelectRowChange({ selectedRows, selectedRowIds }) {
      this.currentWorkshopPlanId = selectedRows[0]?.workshopPlanId
    },
    fetchWorkshopPlanInfo(workshopPlanIds) {
      if (!workshopPlanIds) {
        return
      }
      getAction(this.url.workPlan.list, { workshopPlanIds }).then(res => {
        let { result } = res
        if (result) {
          this.qcPlanReportItemTable.dataSource = result.map(item => {
            return {
              workshopPlanId: item.workshopPlanId,
              orderNumber: item.orderNo,
              materialCode: item.materialCode,
              materialName: item.materialName,
              specificationModel: item.specificationModel,
              formulaNumber: item.formulaNumber
            }
          })
        }
      })
    },
    qcPlanReportItems(workshopPlanId) {
      if (!workshopPlanId) {
        return []
      }
      return this.qcPlanReportItemTable.dataSource.filter(item => {
        return item.workshopPlanId === workshopPlanId
      })
    },
    // 新增检验
    handleAddCard() {
      this.cardList.push({
        standardId: null,
        inspectionDate: this.model.inspectionDate,
        inspectionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 当前时间精确到秒
        inspectionResult: 1, // 默认为合格
        remark: '',
        inspectionItems: []
      });
      this.currentCardIndex = this.cardList.length - 1;
    },
    // 删除卡片
    handleDeleteCard(index) {
      this.cardList.splice(index, 1);
    },
  }
}
</script>

<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled" style="margin-bottom: 8px;">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <j-vxe-table
              style="margin: 9px 0"
              keep-source
              ref="qcPlanReport"
              :loading="qcPlanReportTable.loading"
              :columns="qcPlanReportTableColumns"
              :dataSource="qcPlanReportTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              row-selection-type="radio"
              :toolbar="false"
              @selectRowChange="handleSelectRowChange"
            >
              <template v-slot:formula="{row}">
                <a-select
                  v-model="row.basePowderFormula"
                  placeholder="请选择配方号"
                >
                  <a-select-option
                    v-for="(item,index) in qcPlanReportItems(row.workshopPlanId)"
                    :key="index"
                    :value="item.formulaNumber">
                    {{ item.formulaNumber }}
                  </a-select-option>
                </a-select>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
        <a-row v-if="reportType === 'base-powder'">
          <a-col :span="8">
            <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
              <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- 新增按钮-->
          <a-col :span="2" v-if="reportType === 'base-powder'" style="margin-top:3px">
            <a-button @click="handleAddCard" type="primary" icon="plus">新增</a-button>
          </a-col>
        </a-row>
        <div 
          style="max-height: 600px; 
                  overflow-y: auto; 
                  margin-top: 10px;
                  border: 1px solid #dcdfe6;  /* 添加边框颜色 */
                  border-radius: 4px;         /* 添加圆角 */
                  padding: 10px;              /* 添加内边距 */
                  box-shadow: 0 2px 4px rgba(0,0,0,.1); /* 添加轻微阴影 */
                  margin-bottom: 10px;">
          <el-card v-for="(card, index) in cardList" :key="index"
          style="margin-bottom: 10px;">
            <a-row>
              <!-- 检验标准 -->
              <a-col :span="8">
                <a-form-model-item label="检验标准" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-search-select-tag
                    placeholder="请选择检验标准"
                    @change="handleInspectionStandardChange($event, index)"
                    v-model="card.standardId"
                    :dict="inspectionStandardCode" />
                </a-form-model-item>
              </a-col>
              <!-- 检验日期 -->
              <a-col :span="8" v-if="reportType != 'base-powder'">
                <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
                  <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- 检验时间 -->
              <a-col :span="8" v-if="reportType === 'base-powder'">
                <a-form-model-item label="检验时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-date placeholder="请选择检验时间" date-format='YYYY-MM-DD HH:mm:ss' 
                    v-model="card.inspectionTime" style="width: 100%"></j-date>
                </a-form-model-item>
              </a-col>
              <!-- 删除按钮（第一个卡片不显示） -->
              <a-col :span="2" v-if="reportType === 'base-powder' && index > 0" style="margin-top:3px">
                <a-button @click="handleDeleteCard(index)" type="danger" icon="delete">删除</a-button>
              </a-col>
              <!-- 检验项目表格 -->
              <a-col :span="24">
                <j-vxe-table
                  style="margin: 10px 0"
                  keep-source
                  :ref="'inspectionItemTable_' + index"
                  :loading="qcPlanReportInspectionItemTable.loading"
                  :columns="qcPlanReportInspectionItemTable.columns"
                  :dataSource="card.inspectionItems"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="!formDisabled"
                  :toolbar="true"
                  :toolbarConfig="{
                    slots: ['prefix', 'suffix'],
                    btn: ['remove', 'clearSelection'],
                  }"
                  @remove="(event) => handleDelete(event, index)"
                />
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="检验结果" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                  <j-dict-select-tag type="radio" v-model="card.inspectionResult" dictCode="qc_inspection_result" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                  <a-textarea v-model="card.remark" rows="4" placeholder="请输入备注" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </el-card>
        </div>
        <j-vxe-table
          keep-source
          ref="qcPlanReportItem"
          :loading="qcPlanReportItemTable.loading"
          :columns="qcPlanReportItemTable.columns"
          :dataSource="qcPlanReportItemList"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="false"
          :toolbar="false"
          style="margin-top: 15px;"
        />
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<style scoped>
</style>